import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../controller/admob_controller.dart';
import '../../controller/auth_controller.dart';
import '../../controller/contract_controller.dart';
import '../../model/user_contract_model.dart';
import '../../widgets/invite_rewards_bottom_sheet.dart';

class RunningPlansPage extends StatefulWidget {
  const RunningPlansPage({Key? key}) : super(key: key);

  @override
  _RunningPlansPageState createState() => _RunningPlansPageState();
}

class _RunningPlansPageState extends State<RunningPlansPage> {
  late final ContractController contractController;

  @override
  void initState() {
    super.initState();
    // 确保 ContractController 已被注册
    if (!Get.isRegistered<ContractController>()) {
      Get.put(ContractController());
    }

      if (!Get.isRegistered<AuthController>()) {
      Get.put(AuthController());
    }

      if (!Get.isRegistered<AdMobController>()) {
      Get.put(AdMobController());
    }
    contractController = Get.find<ContractController>();
    // 页面初始化时获取用户合约数据
    _initUserContracts();
  }


   Future<void> _initUserContracts() async {
    await contractController.getUserContractList(showLoading: true);
  }

  Future<void> _loadUserContracts() async {
    await contractController.getUserContractList(showLoading: false);
  }


  
  // 格式化时间戳为可读时间
  String _formatTimestamp(int? timestamp) {
    if (timestamp == null) return '--';
    final date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
    return '${date.year}.${date.month}/${date.day} ${date.hour}:${date.minute.toString().padLeft(2, '0')}:${date.second.toString().padLeft(2, '0')}';
  }
  
  // 构建进度条
  Widget _buildProgressBar(UserContract contract) {
    // 计算进度
    double progress = 0.0;
    final now = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    final startAt = contract.startAt ?? now;
    final endAt = contract.endAt ?? now;
    
    if (endAt > startAt) {
      progress = (now - startAt) / (endAt - startAt);
      // 确保进度在0-1之间
      progress = progress.clamp(0.0, 1.0);
    }
    
    // 根据状态确定颜色
    final isActive = (contract.status ?? -1) == 1; // 假设状态1为活跃状态
    final progressColor = isActive 
        ? const LinearGradient(
            colors: [Color(0xFFFFD700), Color(0xFFE6B450)],
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
          )
        : const LinearGradient(
            colors: [Color(0xFFFF6B6B), Color(0xFFFF9999)],
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
          );
    
    // 非活跃状态显示为淡红色渐变填充整个进度条
    final widthFactor = isActive ? progress : 1.0;
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 开始时间 - 左上方
        Row(
          children: [
            Text(
              _formatTimestamp(contract.startAt),
              style: const TextStyle(
                color: Color(0xFF888888),
                fontSize: 12,
                fontWeight: FontWeight.w400,
              ),
            ),
          ],
        ),
        
        const SizedBox(height: 4),
        
        // 进度条
        Container(
          height: 8,
          width: double.infinity,
          decoration: BoxDecoration(
            color: Colors.grey[800],
            borderRadius: BorderRadius.circular(4),
          ),
          child: FractionallySizedBox(
            alignment: Alignment.centerLeft,
            widthFactor: widthFactor,
            child: Container(
              decoration: BoxDecoration(
                gradient: progressColor,
                borderRadius: BorderRadius.circular(4),
              ),
            ),
          ),
        ),
        
        const SizedBox(height: 4),
        
        // 结束时间 - 右下方
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Text(
              _formatTimestamp(contract.endAt),
              style: const TextStyle(
                color: Color(0xFF888888),
                fontSize: 12,
                fontWeight: FontWeight.w400,
              ),
            ),
          ],
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF1A1A1A),
      appBar: AppBar(
        backgroundColor: Color(0xFF1A1A1A),
        title: Text(
          'My Plans',
          style: TextStyle(color: Colors.white),
        ),
        iconTheme: IconThemeData(color: Colors.white),
        elevation: 0,
        actions: [
          IconButton(
            icon: Text(
              '☰',
              style: TextStyle(color: Colors.white, fontSize: 24),
            ),
            onPressed: () {
              Get.toNamed('/records-detail');
            },
          ),
        ],
      ),
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/running_plans_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Column(
            children: [
              // 计划列表
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  child: RefreshIndicator(
                    color: const Color(0xFFFFD700),
                    backgroundColor: Colors.black.withOpacity(0.8),
                    onRefresh: _loadUserContracts,
                    child: Obx(() {
                      final userContracts = contractController.userContracts;
                      
                      if (contractController.isLoadingUserContracts.value) {
                        return const Center(
                          child: CircularProgressIndicator(
                            color: Color(0xFFFFD700),
                          ),
                        );
                      }
                      
                      if (userContracts.isEmpty) {
                        return ListView(
                          physics: const AlwaysScrollableScrollPhysics(),
                          children: [
                            _buildEmptyState(),
                          ],
                        );
                      }
                      
                      return ListView(
                        physics: const AlwaysScrollableScrollPhysics(),
                        children: [
                          const SizedBox(height: 20),
                          // 使用真实数据构建合约卡片
                          ...userContracts.map((contract) => Padding(
                            padding: const EdgeInsets.only(bottom: 16),
                            child: _buildPlanCardFromContract(contract),
                          )).toList(),
                        ],
                      );
                    }),
                  ),
                ),
              ),
              
              // 底部固定按钮区域
              Container(
                padding: const EdgeInsets.fromLTRB(20, 20, 20, 40), // 增加底部安全区域
                child: Column(
                  children: [
                    // Share & Earn Rewards Button
                    _buildShareButton(context),
                  ],
                ),
              ),
            ],
          ),
        ),
      
    );
  }

  // 已删除 _buildHeader() 方法，改用 AppBar 实现



  // 已删除 _buildWatchAdsButton 方法
   // 添加防抖变量
  bool _isWatchAdsButtonEnabled = true;
  Widget _buildShareButton(BuildContext context) {
    return Container(
      width: double.infinity,
      height: 48, // 稍微小一点的高度
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [Color(0xFFFFD700), Color(0xFFFFA500)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(24),
        boxShadow: [
          BoxShadow(
            color: const Color(0xFFFFD700).withOpacity(0.3),
            blurRadius: 8,
            spreadRadius: 1,
          ),
        ],
      ),
      child: Container(
        margin: const EdgeInsets.all(1.5),
        decoration: BoxDecoration(
          color: const Color(0xFF1A1A1A),
          borderRadius: BorderRadius.circular(22),
        ),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            borderRadius: BorderRadius.circular(22),
            onTap: 
             _isWatchAdsButtonEnabled ? () {
            // 设置防抖，禁用按钮
            setState(() {
              _isWatchAdsButtonEnabled = false;
            });
            
            // 2秒后重新启用按钮
            Future.delayed(const Duration(seconds: 2), () {
              if (mounted) {
                setState(() {
                  _isWatchAdsButtonEnabled = true;
                });
              }
            });
            final authController = Get.find<AuthController>();
            if (authController.isLoggedIn.value) {
              // 已登录：展示广告，使用RUNNING_PLAN_AD_UNIT广告单元
              final adMobController = Get.find<AdMobController>();
               adMobController.showRewardedAd(
                    adUnitId: AdMobController.FREE_PLAN_AD_UNIT,
                    onUserEarnedReward: (ad, reward) async {
                      // 延迟2秒后执行广告合约创建和刷新
                      Future.delayed(const Duration(seconds: 1), () async {
                         contractController.getUserContractList(showLoading: true);
                      });
                    },
                  );
            } else {
              // 未登录：显示登录弹窗
              authController.showLoginDialog();
            }
          } : null,
            // () {
            //  showModalBottomSheet(
            //   context: context,
            //   isScrollControlled: true,
            //   backgroundColor: Colors.transparent,
            //   builder: (context) => InviteRewardsBottomSheet(),
            // );
            // },
            child: Center(
              child: ShaderMask(
                shaderCallback: (Rect bounds) {
                  return const LinearGradient(
                    colors: [Color(0xFFFFD700), Color(0xFFFFA500)],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ).createShader(bounds);
                },
                child: const Text(
                  'Watch Ads to Add Time',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    letterSpacing: 1.0,
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  // 空状态显示
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.description_outlined,
            color: Colors.grey[400],
            size: 64,
          ),
          const SizedBox(height: 16),
          Text(
            'No Running Plans',
            style: TextStyle(
              color: Colors.grey[400],
              fontSize: 18,
              fontWeight: FontWeight.w500,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            'Start mining to see your active contracts here',
            style: TextStyle(
              color: Colors.grey[500],
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }

  // 根据UserContract构建计划卡片
  Widget _buildPlanCardFromContract(UserContract contract) {
    final statusColor = contractController.getStatusColor(contract.status ?? -1);
    final statusText = contractController.getStatusText(contract.status ?? -1);
    
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.transparent,
        border: Border.all(
          color: const Color(0xFFE6B450),
          width: 1,
        ),
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 状态标签和标题
          Row(
            children: [
              // 状态标签
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: statusColor.withOpacity(0.2),
                  border: Border.all(color: statusColor, width: 1),
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Text(
                  statusText,
                  style: TextStyle(
                    color: statusColor,
                    fontSize: 12,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              
              const SizedBox(width: 12),
              
              // 计划标题
              Expanded(
                child: Text(
                  contract.safeTitle,
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ],
          ),
          
          const SizedBox(height: 16),
          
          // 算力值
          ShaderMask(
            shaderCallback: (Rect bounds) {
              return const LinearGradient(
                colors: [Color(0xFFFFD700), Color(0xFFFFA500)],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ).createShader(bounds);
            },
            child: Text(
              '${contract.describe ?? '--'}',
              style: const TextStyle(
                color: Colors.white,
                fontSize: 32,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          
          const SizedBox(height: 8),
          
          // 进度条和时间显示
          const SizedBox(height: 12),
          
          // 进度条
          _buildProgressBar(contract),
        ],
      ),
    );
  }
}